<template>
  <a-modal
    :title="modalTitle"
    :width="850"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @cancel="handleCancel"
  >
    <a-form :form="form">
      <a-form-item v-show="false" >
        <a-input v-decorator="['id']" type="hidden"/>
      </a-form-item>

      <a-form-item v-show="false" >
        <a-input v-decorator="['sbId']" type="hidden"/>
      </a-form-item>
      <a-form-item v-show="false" >
        <a-input v-decorator="['sbPartId']" type="hidden"/>
      </a-form-item>

      <a-form-item v-show="false" >
        <a-input v-decorator="['spareId']" type="hidden"/>
      </a-form-item>

      <a-form-item v-show="false" >
        <a-input v-decorator="['oldSpareId']" type="hidden"/>
      </a-form-item>

      <a-row class="form-row" :gutter="BaseTool.Constant.row.gutter">
        <a-col :lg="12" :md="24" :sm="24">
          <a-form-item
            label="选择备件"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-input
              style="width: 70%"
              disabled
              v-decorator="['spareName', {rules: [{required: true, message: '备件不能为空'}]}]" />
            <a-button style="width: 30%" type="primary" @click="handleSpareSelect">选择</a-button>
          </a-form-item>
        </a-col>
        <a-col :lg="12" :md="24" :sm="24">
          <a-form-item
            label="维护部位"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-input
              disabled
              style="width: 80%"
              v-decorator="['sbPartName', {rules: [{required: false, message: '维护部位不能为空'}]}]"/>
            <a-button type="primary" style="width: 20%" @click="handlePartSelect">选择</a-button>
          </a-form-item>
        </a-col>
        <a-col :lg="12" :md="24" :sm="24">
          <a-form-item
            label="更换周期"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
            style="margin-bottom:0;"
          >
            <!-- 解决校验问题 -->
            <a-form-item :style="{ display: 'inline-block', width: '60%' }">
              <a-input-number
                :min="1"
                style="width: 100%"
                v-decorator="['period', {initialValue: 500,rules: [{required: true, message: '更换周期不能为空'}]}]"/>
            </a-form-item>
            <a-form-item
              :style="{ display: 'inline-block', width: '40%' }"
            >
              <a-select
                v-decorator="['periodType', {initialValue: 6,rules: [{required: true, message: '周期类型不能为空'}]}]"
                placeholder="请选择">
                <a-select-option
                  v-for="(label,value) in periodTypeMap"
                  :key="value"
                  :label="label"
                  :value="parseInt(value)">{{ label }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-form-item>
        </a-col>
        <a-col :lg="12" :md="24" :sm="24">
          <a-form-item
            label="数量"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-input-number
              style="width: 100%"
              :min="0"
              :step="1"
              :formatter="BaseTool.Amount.formatter"
              :parser="BaseTool.Amount.parser"
              v-decorator="['num', {initialValue:1, rules: [{required: true, message: '数量不能为空'}]}]" />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>

    <spare-part-info-select-modal :type="'checkbox'" ref="spareSelectModal" @selected="handleSpareSelected"/>
    <part-info-select-modal ref="partInfoSelectModal" @selected="handlePartSelected"/>
    <template slot="footer">
      <a-button :loading="confirmLoading" type="primary" @click="save()">保存</a-button>
    </template>
  </a-modal>
</template>

<script>
import pick from 'lodash.pick'
import { addSbModelBom, updateSbModelBom, deleteSbModelBoms } from '@/api/sb/modelbom'
import SparePartInfoSelectModal from '@/views/sqarepartmanage/sparepartinfo/modules/SparePartInfoSelectModal'
import PartInfoSelectModal from '@/views/part/info/modules/PartInfoSelectModal'
export default {
  name: 'BaseSbModel',
  data () {
    return {
      confirmLoading: false,
      sbId: null,
      spareId: null,
      modalTitle: null,

      form: this.$form.createForm(this),
      visible: false,
      // 下拉框map,
      enableMap: {},
      statusMap: {},
      sbTypeTreeData: [],
      typeMap: {},
      periodTypeMap: {}
    }
  },
  components: {
    SparePartInfoSelectModal,
    PartInfoSelectModal
  },
  created () {
    // 下拉框map
    this.depreciationTypeMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.SBINFO_DEPRECIATIONTYPE)
    this.levelMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.SBINFO_LEVEL)
    this.statusMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.SB_MODEL_RECOMMEND)
    this.unitMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.SBINFO_UNIT)
    this.enableMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.YES_NO)
    this.typeMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.CHECK_STANDARD_TYPE)
    this.useTypeMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.SB_UES_TYPE)
    this.periodTypeMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.CHECK_PLAN_PERIOD_TYPE)
  },
  methods: {
    base (record) {
      this.visible = true
      if (this.BaseTool.Object.isBlank(record.id)) {
        this.sbId = record.sbId
        this.modalTitle = '添加'
        const { form: { setFieldsValue } } = this
        // 日期处理
        this.$nextTick(() => {
          setFieldsValue(Object.assign({
            'sbId': record.sbId
          }))
        })
        return
      }
      this.modalTitle = '编辑'
      record.oldSpareId = record.spareId
      const { form: { setFieldsValue } } = this
      record.spareName = record.name
      // 日期处理
      this.$nextTick(() => {
        setFieldsValue(Object.assign(pick(record, [
          'id',
          'sbId',
          'sbPartId',
          'spareId',
          'sbPartName',
          'spareName',
          'period',
          'periodType',
          'num',
          'oldSpareId'
        ])))
      })
    },

    handleCancel (values) {
      this.visible = false
      this.confirmLoading = false
      this.form.resetFields()
      if (this.BaseTool.Object.isNotBlank(values)) {
        this.$emit('ok', values)
      }
    },

    save () {
      const { form: { validateFieldsAndScroll } } = this
      this.confirmLoading = true
      validateFieldsAndScroll((errors, values) => {
        if (errors) {
          this.confirmLoading = false
          return
        }
        if (this.BaseTool.String.isBlank(values.id)) {
          addSbModelBom(values)
            .then((response) => {
              this.$message.info('添加成功')
              this.handleCancel(values)
            }).catch(() => {
              this.confirmLoading = false
            })
        } else {
          updateSbModelBom(values)
            .then(() => {
              this.handleCancel(values)
            }).catch(() => {
              this.confirmLoading = false
            })
        }
      })
    },

    handleSpareSelect () {
      this.$refs.spareSelectModal.base({})
    },
    handleSpareSelected (record, keys, rows) {
      const [ key ] = keys
      const [ row ] = rows
      const { form: { setFieldsValue } } = this
      // 日期处理
      this.$nextTick(() => {
        setFieldsValue(Object.assign({
          'spareId': key,
          'spareName': row.name
        }))
      })
    },
    handleDel () {
      const data = [...this.data]
      let ids = []
      ids = this.selectedRows.map(item => item.bomId)

      // 调取删除接口，批量删除
      this.confirmLoading = true
      deleteSbModelBoms(ids)
        .then(() => {
          this.data = data.filter(item => !this.selectedRowKeys.includes(item.id))
          this.handleCancel()
          this.$message.info('删除成功')
        }).catch(() => {
          this.confirmLoading = false
        })
    },
    handlePartSelect () {
      const sbId = this.form.getFieldValue('sbId')
      this.$refs.partInfoSelectModal.base({ sbId })
    },
    handlePartSelected (keys, rows) {
      const [ key ] = keys
      const [ row ] = rows
      const { form: { setFieldsValue } } = this
      this.$nextTick(() => {
        setFieldsValue(Object.assign({
          'sbPartId': key,
          'sbPartName': row.name
        }))
      })
    }
  }
}
</script>
